﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AllenData
{
    public class NeighborData
    {
        public Neighbor GetNeighbor(int neighborId)
        {
            using (var ctx = new AllenNeighborhoodEntities())
            {
                var neighbor = ctx.Neighbors.Where(n => n.NeighborID == neighborId);
                return neighbor.FirstOrDefault();
            }
        }

        public List<Neighbor> GetAllNeighbors()
        {
            using (var ctx = new AllenNeighborhoodEntities())
            {
                return ctx.Neighbors.ToList();
            }
        }

        public List<Neighbor> GetNeighbors(string streetNumber, int streetID)
        {
            using (var ctx = new AllenNeighborhoodEntities())
            {
                return ctx.Neighbors.Where(c => c.StreetNumber.ToUpper() == streetNumber.ToUpper() && c.StreetID == streetID).ToList();
            }
        }

        public int AddNewNeighbor(Neighbor neighbor)
        {
            using (var ctx = new AllenNeighborhoodEntities())
            {
                ctx.AddToNeighbors(neighbor);
                ctx.SaveChanges();

                Neighbor newNeighbor = ctx.Neighbors.Where(
                    n => n.FirstName == neighbor.FirstName).FirstOrDefault();

                if (newNeighbor == null)
                    return -1;
                else
                    return newNeighbor.NeighborID;
            }
        }

        public void UpdateNeighbor(Neighbor neighbor)
        {
            using (var ctx = new AllenNeighborhoodEntities())
            {
                Neighbor dbDept = ctx.Neighbors.First(n => n.NeighborID == neighbor.NeighborID);
                ctx.ApplyCurrentValues("Neighbors", neighbor);
                ctx.SaveChanges();
            }
        }

        public void DeleteNeighbor(int neighborId)
        {
            using (var ctx = new AllenNeighborhoodEntities())
            {
                Neighbor dbDept = ctx.Neighbors.First(n => n.NeighborID == neighborId);
                ctx.DeleteObject(dbDept);
                ctx.SaveChanges();
            }
        }

    }
}
